import React from 'react';
import axios from 'axios';
import { PieChart, Pie, Legend, Tooltip, ResponsiveContainer } from 'recharts';
import { useState ,useEffect} from 'react';
import  { PureComponent } from 'react';
import { BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid } from 'recharts';
import AppBar from '@mui/material/AppBar';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import IconButton from '@mui/material/IconButton';
import SearchIcon from '@mui/icons-material/Search';
import RefreshIcon from '@mui/icons-material/Refresh';
import ListSubheader from '@mui/material/ListSubheader';
import List from '@mui/material/List';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import Collapse from '@mui/material/Collapse';
import InboxIcon from '@mui/icons-material/MoveToInbox';
import DraftsIcon from '@mui/icons-material/Drafts';
import SendIcon from '@mui/icons-material/Send';
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import StarBorder from '@mui/icons-material/StarBorder';
import PersonIcon from '@mui/icons-material/Person';
import HistoryIcon from '@mui/icons-material/History';
import AccountBalanceIcon from '@mui/icons-material/AccountBalance';
import PaymentIcon from '@mui/icons-material/Payment';
import Box from '@mui/material/Box';
import Input from '@mui/material/Input';

const ariaLabel = { 'aria-label': 'description' };

const data01 = [
  { name: 'Group A', value: 400 },
  { name: 'Group B', value: 300 },
  { name: 'Group C', value: 300 },
  { name: 'Group D', value: 200 },
  { name: 'Group E', value: 278 },
  { name: 'Group F', value: 189 },
];

const data = [
  {
    name: 'Page A',
    uv: -4000,
    
    amt: 2400,
  },
  {
    name: 'Page B',
    uv: 3000,
    pv: 1398,
    amt: 2210,
  },
  {
    name: 'Page C',
    uv: -2000,
    pv: 9800,
    amt: 2290,
  },
  {
    name: 'Page D',
    uv: 2780,
    pv: 3908,
    amt: 2000,
  },
  {
    name: 'Page E',
    uv: 1890,
    pv: 4800,
    amt: 2181,
  },
  {
    name: 'Page F',
    uv: 2390,
    pv: 3800,
    amt: 2500,
  },
  {
    name: 'Page G',
    uv: 3490,
    pv: 4300,
    amt: 2100,
  },
];



export default function Content() {
  const [open, setOpen] = React.useState(true);
  const [rows2, setRows2] = useState([]);
  const [rows1, setRows1] = useState(0);

  const [formValues, setFormValues] = useState({
    amounts: ['', '', '', '', '', '']
  });

  const sell_stock = new FormData();
  //data_stock.append('stockname', '弘讯科技');





  useEffect(() => {
    axios.get('http://172.24.56.192:5000/index/myassets',{headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
              }})
                .then(function (response) {
                    // 这里是处理响应的代码
                  // var code = response['code']
                  setRows2(response.data['data']);
                  setRows1(response.data['stock_num']);
                  console.log(rows1);
                  console.log(response.data);
                    
                })
                .catch(function (error) {
                    // 这里是处理错误的代码
                  // window.location.href="https://www.baidu.com/"
                    console.log(error);
                  
                });},[]);



const handleClick = ()  => {
    console.log(formValues);
    //let value= formData.amount
    let i = 0;
    let amount_stock = ''
    let flag = 0;
    for ( i = 0; i < formValues.amounts.length; i++) {
      const amount = formValues.amounts[i];
      if (amount.trim() !== '') {
        flag = 1
        amount_stock = amount;
        console.log(`Amount at index ${i} is not empty.`);
        break;
      }
    }
    
    if(flag === 1) {
      sell_stock.append('stock_name',rows2[i]['name']);
      sell_stock.append('amount',amount_stock);



    }
   

    
    

    setOpen(!open);

    axios.post('http://172.24.56.192:5000/index/myassets',sell_stock ,{headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
      }})
      .then(response => {
        // 处理成功响应
        console.log(response.data);
        if(response.data['code'] == 200)
        {
            alert('Success')
            window.location.href="AppHome_Inv_1"
            
        }
      })
      .catch(error => {
        // 处理错误
        console.error(error);
        // 在这里进行其他操作，如显示错误提示等
      });



  };

  const handleInputChange = (event, index) => {
    const { value } = event.target;
    setFormValues(prevState => {
      const updatedAmounts = [...prevState.amounts];
      updatedAmounts[index] = value;
      return { ...prevState, amounts: updatedAmounts };
    });
  };

  const componentInstances = [];
  for (let i = 0; i < rows1; i++) {
    componentInstances.push(
      <Grid container spacing={2}>
        <Grid item xs={2}>
          <ListItemButton>
            <Typography>  
            {rows2[i]['name']}
            </Typography>
          </ListItemButton>
        </Grid>
  
        <Grid item xs={2}>
          <ListItemButton>
            <Typography>
            {rows2[i]['num']}
            </Typography>
          </ListItemButton>
        </Grid>
  
        <Grid item xs={2}>
          <ListItemButton>
            <Typography>
            {rows2[i]['price']}
            </Typography>
          </ListItemButton>
        </Grid>
  
        <Grid item xs={4}>
          <Box
            component="form"
            sx={{
              '& > :not(style)': { m: 0 },
              height: '50px'
            }}
            noValidate
            autoComplete="off"
          >
            <Input
              placeholder="Amount"
              value={formValues.amounts[i]}
              onChange={event => handleInputChange(event, i)}
            />
          </Box>
        </Grid>
  
        <Grid item xs={2}>
          <Button variant="outlined" color="success" onClick={() => handleClick()}>
            Sell
          </Button>
        </Grid>
      </Grid>
    );
  }
  

  return (
    <Paper sx={{ maxWidth: 2000, margin: 'auto', overflow: 'hidden' }}>
      



          <List
            sx={{ width: '100%', maxWidth: 2000, bgcolor: 'background.paper' }}
            component="nav"
            aria-labelledby="nested-list-subheader"
          >



            <Grid container spacing={2}>

              <Grid item xs={2}> 
                <ListItemButton>
                  <ListItemText primary="My Stocks" primaryTypographyProps={{color: 'primary'}}/>  
                </ListItemButton>
              </Grid> 

              <Grid item xs={2}>
                <ListItemButton>
                  <ListItemText primary="Amount of Stocks" primaryTypographyProps={{color: 'primary'}}/>  
                </ListItemButton> 
              </Grid>  
              
              <Grid item xs={8}>
                <ListItemButton>
                  <ListItemText primary="Price of Stocks" primaryTypographyProps={{color: 'primary'}}/>  
                </ListItemButton> 
              </Grid>  


             
            





            </Grid>

            {componentInstances}






            
          </List>
          
        <Grid container spacing={15}>
          <Grid item xs={4.5} style={{ marginLeft: '120px' }}>
        <PieChart width={300} height={300}>
          <Pie
            dataKey="num"
            isAnimationActive={false}
            data={rows2}
            cx="50%"
            cy="50%"
            outerRadius={80}
            fill="#8884d8"
            label
          />
          <Tooltip />
          
          
        </PieChart>
        <Typography variant="h7" component="div" align="center"color="primary">
      股票数量图
    </Typography>
        </Grid>
        <Grid item xs={6} style={{ marginRight: '10px' }} >
        <PieChart width={300} height={300}>
          <Pie
            dataKey="total_amt"
            isAnimationActive={false}
            data={rows2}
            cx="50%"
            cy="50%"
            outerRadius={80}
            fill="#FA7F6F"
            label
          />
          <Tooltip />
        </PieChart>
        <Typography variant="h7" component="div" align="center"color="primary">
      股票价值图　　　　　　　　　　　　　　　　
    </Typography>
        </Grid>
        
        </Grid>
       

        
    </Paper>
  );
}

